<?php
    class OptionsController
    {
        private $model;
        private $view;
        
        public function __construct($model, $view) {
            $this->model = $model;
            $this->view  = $view;
            $view->setController($this);
        }
        
        // Parse the actions
        public function parseActions() {
            // See if there are actions to be taken:
            if(isset($_POST['save'])) {
                // Save the option:
                $name        = makeSafe($_POST['name']);
                $description = makeSafe($_POST['description']);
                $type        = makeSafe($_POST['type']);
                $value       = makeSafe($_POST['value']);
                if($type=='category') { $value=makeSafe($_POST['id_category']); }
                if($type=='url'&&empty($value)) { $value='http://'; }
                $action      = makeSafe($_POST['action']);                
                $values = array('name'=>$name, 'description'=>$description, 'type'=>$type, 'value'=>$value);
                if($action=='add') {
                    $this->model->addOption($values);
                } elseif($action=='edit') {
                    $id = $_POST['id'];
                    $this->model->updateOption($id, $values);
                }
            } elseif(isset($_POST['delete'])) {
                // Delete the option:
                $id = $_POST['id'];
                $this->model->deleteOption($id);
            }
        }
        
        // Render the view
        public function render() {
            // Show the interface:
            $this->view->showTop();
            if(isset($_POST['add'])) {
                $values = array('name'=>'', 'description'=>'', 'type'=>'text', 'value'=>'', 'id'=>'', 'action'=>'add');
                $this->view->showForm($values);
            } elseif (isset($_POST['edit'])) {
                $id               = $_POST['id'];
                $values           = $this->model->getOption($id);
                $values['action'] = 'edit';
                $this->view->showForm($values);
            } else {                
                $records = $this->model->getRecords();
                if(count($records)==0) {
                    $this->view->showNoRecordsAvailable();    
                } else {
                    $this->view->showRecords($records);
                }
                $this->view->showAddEditDelete();
            }
            $this->view->showBottom();
        }
        
        // Return an array of available option types
        public function getTypes() {
            return $this->model->getTypes();
        }
        
        // Return an array with available categories
        public function getCategories() {
            return $this->model->getCategories();
        }
    }
?>